package com.zklh.leetcode.top100;

import com.zklh.leetcode.tree.model.ListNode;

/**
 * K位一组反转链表
 *
 * @version 1.0
 * @Author tongnan
 * @Date 2023/10/23
 */
public class Solution25 {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode preHead = new ListNode();
        ListNode preStart = preHead;
        ListNode start = head;
        ListNode next = null;
        while (start != null) {
            ListNode end = start;
            int len = 1;
            while (end.next != null && len < k) {
                end = end.next;
                len++;
            }
            if (len == k) {
                // 断掉链表
                next = end.next;
                end.next = null;
                preStart.next = reverseList(start);
                preStart = start;
                // 续上断掉的链表
                preStart.next = next;
                start = next;
            } else {break;}

        }
        return preHead.next;
    }

    private ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode current = head;
        ListNode temp;
        while (current != null) {
            temp = current.next;
            current.next = prev;
            prev = current;
            current = temp;
        }
        return prev;
    }

    public static void main(String[] args) {
        Solution25 solution25 = new Solution25();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        System.out.println(solution25.reverseKGroup(head,1 ));
    }

}